﻿using System;
using IrelandAlt.ORNetTwitt.SimpleRepository;
using OpenRasta.Web;
using IrelandAlt.ORNetTwitt.Resources;

namespace IrelandAlt.ORNetTwitt.Handlers
{
    public class HandlerHelper
    {
        public static IUserSecurity GetUserSecurityContext(ICommunicationContext communicationContext)
        {
            if (communicationContext == null) throw new ArgumentNullException("communicationContext");

            var userSec = communicationContext.User as UserUiResource;            

            // if we already have the user in the context go on?
            if (userSec != null) if (userSec.UserId > 0 && userSec.Identity.IsAuthenticated) return userSec;
                        
            return GetNewUserSecurityFromContext(communicationContext);
        }

        private static IUserSecurity GetNewUserSecurityFromContext(ICommunicationContext communicationContext)
        {
            var userSec = new UserUiResource(communicationContext.User.Identity);

            GetUserFromRepository(communicationContext, userSec);

            // save the user in our our context...
            communicationContext.User = userSec;

            return userSec;
        }

        private static void GetUserFromRepository(ICommunicationContext communicationContext, IUserSecurity userSec)
        {
            if (userSec.Identity.Name == string.Empty) return;
                
            new UserDa().GetUserDetails(communicationContext.User.Identity.Name, userSec);
        }
    }
}